package leetcode.code0636;

import java.util.Arrays;
import java.util.List;
import java.util.Stack;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution2 implements IDebug {

	public int[] exclusiveTime(int n, List<String> logs) {
		int len = logs.size();
		int[][] log = new int[len][3];
		for (int i = 0; i < logs.size(); i++) {
			String[] _logs = logs.get(i).split(":");
			int id = Integer.valueOf(_logs[0]);
			int status = _logs[1].equals("start") ? 1 : 0;
			int time = Integer.valueOf(_logs[2]);
			log[i] = new int[] { id, status, time };
		}
//		Arrays.sort(log, (a, b) -> a[2] == b[2] ? a[0] == b[0] ? b[1] - a[1] : a[0] - b[0] : a[2] - b[2]);
		int[] ans = new int[n];
		Stack<int[]> stack = new Stack<>();
		for (int i = 0; i < len; i++) {
			int id = log[i][0], status = log[i][1], time = log[i][2];
			if (status == 1) {
				stack.add(new int[] { time, 0 });
			} else {
				int[] s = stack.pop();
				int cur = time - s[0] + 1 - s[1];
				ans[id] += cur;
				if (!stack.isEmpty()) {
					stack.peek()[1] += cur + s[1];
				}
			}
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(H.str2array3("[6]"), this.exclusiveTime(1,
				H.str2liststr("[\"0:start:0\",\"0:start:1\",\"0:start:2\",\"0:end:3\",\"0:end:4\",\"0:end:5\"]")));
		H.compare(H.str2array3("[8]"), this.exclusiveTime(1,
				H.str2liststr("[\"0:start:0\",\"0:start:2\",\"0:end:5\",\"0:start:6\",\"0:end:6\",\"0:end:7\"]")));
		H.compare(H.str2array3("[7,1]"), this.exclusiveTime(2,
				H.str2liststr("[\"0:start:0\",\"0:start:2\",\"0:end:5\",\"1:start:6\",\"1:end:6\",\"0:end:7\"]")));
		H.compare(H.str2array3("[3,4]"),
				this.exclusiveTime(2, H.str2liststr("[\"0:start:0\",\"1:start:2\",\"1:end:5\",\"0:end:6\"]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
